Search code examples
pythonbuttonuser-interfacetkintermessagebox

Connect a message box to a button


I want to be able to click the button and have the message box display the code generated. Here's part of the code:

global s
letters = [random.choice('BCDFGHJKMPQRTVWXYYZ')  for x in range(19)]
numbers = [random.choice('2346789') for x in range(6)]
s = letters + numbers
random.shuffle(s)
s = ''.join(s)

global Code
Code = Entry(state='readonly')

def callback():
    Code = Entry(state='readonly', textvariable=s)

Code.grid(row=0, pady=20)
generate=PhotoImage(file='generate.gif')
G = Button(image=generate , command=callback, compound=CENTER)
G.grid(row=1, padx=206.5, pady=20) 

Solution

  • Fixed a few things up with comments:

    from Tkinter import *
    import random
    root = Tk()
    
    letters = [random.choice('BCDFGHJKMPQRTVWXYYZ')  for x in range(19)]
    numbers = [random.choice('2346789') for x in range(6)]
    s = letters + numbers
    random.shuffle(s)
    s = ''.join(s)
    
    # Rather than use global variables, which is generally a bad idea, we can make a callback creator function, which takes the formerly global variables as arguments, and simply uses them to create the callback function.
    def makeCallback(sVariable):
        def callback():
    # This will set the text of the entry
            sVar.set(s)
        return callback
    
    # Use a StringVar to alter the text in the Entry
    sVar = StringVar(root)
    # You can use an Entry for this, but it seems like a Label is more what you're looking for.
    Code = Entry(root, state='readonly', textvariable=sVar)
    
    # Create a callback function
    callback = makeCallback(sVar)
    
    Code.grid(row=0, pady=20)
    generate=PhotoImage(file='generate.gif')
    G = Button(root, image=None , command=callback, compound=CENTER)
    G.grid(row=1, padx=206.5, pady=20)