2014-04-28 54 views
0

我是编程和python的新手,并且使用输出和输入控制台编写了一个简单的基于文本的RPG。我想更改为使用tkinter将文本输出到小部件,并通过键盘按键进行按键输入。得到tkinter窗口布局后,我想如何,我只是不知道如何获得不同的输入来使用tkinter事件。Python tkinter:用按键替换输入?

def main_menu(hero): 
choice = ' ' 
while choice not in ['0', '1', '2', '3']: 
     while choice != '0' and hero.health > 0: 
      print("\n" * 80) 
      print(hero) 
      print("Where would you like to go?\n" 
          "[1] Adventure\n" 
          "[2] Temple\n" 
          "[3] Store\n\n" 
          "[0] Save & Quit") 
      choice = input(">") 
      if choice == '1': 
       adventure(hero) 
      elif choice == '2': 
       temple(hero) 
      elif choice == '3': 
       store(hero) 
      elif choice == '0': 
       save(hero) 

而当通过的Tkinter为选择输入已取得我希望它继续向下到下一个功能例如店()这里我想从Tkinter的一个新的输入来解决这函数调用next

def store(hero): 
    item_type = '' 
    while item_type not in ['1', '2', '3']: 
     print("\n" * 80) 
     print("What would you like to buy?" 
        "\n[1] Weapons" 
        "\n[2] Armor" 
        "\n\n[3] Leave") 
     item_type = str(input(">")) 
     if item_type == '1': 
      weapon_store(hero) 
      item_type = '' 
     elif item_type == '2': 
      armor_store(hero) 
      item_type = '' 
     else: 
      input("Okay, have a good day.\n") 

回答

0

如果我正确地得到你,

我想改变使用tkinter将文本输出到小部件中

为此,我们使用Labels。让我们来简单的例子:

var = StringVar() 
label = Label(root, textvariable=var, relief=RAISED) 

var.set("Hey!? How are you doing?") 
label.pack() 

这是用于设置label.You一个字符串变量&你可以改变它,只要你愿意。通过键盘

按键输入按下

def key(event): 
    print "pressed", repr(event.char) 

def callback(event): 
    frame.focus_set() 
    print "clicked at", event.x, event.y 

frame = Frame(root, width=100, height=100) 
frame.bind("<Key>", key) 
frame.bind("<Button-1>", callback) 
frame.pack() 

如果您运行此脚本,你会发现,你在框点击它开始接收任何键盘事件之前。

查看更多about events and bindings at effbot

+0

我想我应该更清楚我的问题是什么。当我运行mainloop()来启动GUI时,我不知道如何让它进入main_menu函数,而不必在主循环的每一次迭代中输入它。 我不知道整个绑定的事情。我想要它做的是启动GUI,然后输入main_menu()函数,并在不同的函数中,我希望从键盘获得新的输入,并有一个很好的方法来根据输入做什么来更新不同的标签在函数中。 – user3579548

+0

然后在接受你自己的回答之前,重新框架你的问题:) – Gogo

0

我设法解决我的问题,通过更改按键作为StringVar,然后在代码中使用wait_variable我希望它接收新的输入。