简体   繁体   中英

How to make Button to be input to a variable on Python 3 with Tkinter

I want to make a simple hangman game with the tkinter module on Python 3. I'm done making all the alphabet buttons.

from tkinter import *

from tkinter import messagebox

top = Tk()


top.resizable(0,0)
top.geometry("300x250")
def helloCallBack():
   msg = messagebox.showinfo( "Hello Python", 'HI')
def buttonhuruf():
   A = Button(top, text = "A", command = helloCallBack)
   B = Button(top, text = "B", command = helloCallBack)
   C = Button(top, text = "C", command = helloCallBack)

   A.place(x = 50,y = 110)
   B.place(x = 70,y = 110)
   C.place(x = 90,y = 110)


buttonhuruf()
top.mainloop()

How can I make each button be an input variable, like if I press the A Button, the variable press = 'A'

You can generate an event to simulate someone hitting a key on the keyboard. Check out http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html for more details. But, you could change your code to pass in the key to press via the Button, and the handler to do something with it. So...

def helloCallBack():
   msg = messagebox.showinfo( "Hello Python", 'HI')
def buttonhuruf():
   A = Button(top, text = "A", command = helloCallBack)

could become

def helloCallBack(key):
   msg = messagebox.showinfo( "Hello Python", 'HI, %s!' % key)
   top.event_generate(key)
def buttonhuruf():
   A = Button(top, text = "A", command = lambda k='A':helloCallBack(k))
   # similar for B, C, etc...

Give this a try and see where it brings you.

You still need to add widgets to display the key presses. You'll need that to implement your Hangman game.

Above you can see how to pass a particular key to your handler. Depending on how you implement your game, the handler would probably put the character into some widget rather than mimicking a keyboard entry.

Also, to save yourself some typing and make the code more maintainable:

def buttonhuruf():
    d = {}
    for ch in list('ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
        d[ch] = Button(top, text=ch, command=lambda k=ch: helloCallBack(k))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM