2016-05-17 61 views
0

解决 - 答案发现@How to take input from Tkinter使用功能 - 如何传递和返回变量部件

有一个问题 - 我试图复制这个例子的样式在解决链路,虽然我一直在我自己的一些格式化的。我发现如果获得返回值的对象是用其他点添加的,例如把.pack()或在我的情况下.grid()与对象所在的行放在同一行上创建,当你尝试传回变量时它会抛出一个错误。因此,请继续并使用第二行.pack().grid()

原帖

我有一个程序,在命令行中工作正常,我试图给它一个GUI。不幸的是,我仍然对如何在界面中使用函数/方法/命令感到困惑。

我的例子是使用一个按钮来获得从用户获得输入后的所有内容。在命令行程序中,用户输入作为变量传递给一个函数并返回其他三个变量。这三个变量被传递给另一个函数以提供结果,然后将结果格式化以显示。

那么,我试图使用tkinter。我有一个输入字段,它将用户输入分配给一个变量。我有一个按钮链接到一个函数,这意味着开始滚动......我不知道如何将该变量发送到所需的函数,或者如何获取返回的变量并应用它。在我的具体示例中,我想将变量“notation”发送到函数“parse()”,“parse()”的输出将被发送到“roll()”,并且“roll()”的输出发送到变量“输出”然后显示。所有这些都将使用带有“command = calculate”的按钮开始,“calculate()”是一个可以让整个球滚动的函数。

我非常抱歉...我完全自学,我相信我甚至没有使用正确的术语。我也明白,这个例子不是非常pythonic - 我最终将所有这些放到类中,并将函数改为方法,但现在我只想看看它的工作。

这是目前为止的代码。公平的警告,这不是我唯一的问题...我只想坚持一个问题,直到我能解决它。

#!/usr/bin/env python 

from tkinter import * 
from tkinter import ttk 
import re 
import random 

# Parsing function from the original command line tool 
# Turns dice notation format into useful variables 

def parse(d): 
    dice, dtype_mod = d.split('d') 

    dnum = 1 
    dtype = 6 
    mod = 0 

    if dtype_mod: 
     if '-' in dtype_mod: 
      dtype, mod = dtype_mod.split('-') 
      mod = -1 * int(mod) 
     elif '+' in dtype_mod: 
      dtype, mod = dtype_mod.split('+') 
      mod = int(mod) 
     else: 
      dtype = dtype_mod 
    if not dtype: dtype = 6 
    if not mod: mod = 0 

    return (int(dice), int(dtype), int(mod)) 

# Rolling function from the original command line tool 
# 'print()' will be changed into a variable, with the output 
# appended in the working version. 

def roll(a, b): 
    rolls = [] 
    t = 0 

    for i in range(a): 
     rolls.append(random.randint(1, b)) 
     t += int(rolls[i]) 
     print(('Roll number %d is %s, totaling %d') % (i + 1, rolls[i], t)) 
    return (int(t)) 

# Placeholder - the rest of the command line code will be used here later 
# This code will be what starts everything rolling. 
# For debugging, attempting to pass a variable, doing it wrong. 

def calculate(): 
    output = "this is something different" 
    return output 

# Initialize 

dice = Tk() 
dice.title('Roll the Dice') 
dice.geometry("800x600+20+20") 

# Drawing the main frame 

mainframe = ttk.Frame(dice, padding="3 3 12 12") 
mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) 
mainframe.columnconfigure(0, weight=1) 
mainframe.rowconfigure(0, weight=1) 

# Variables needed for program and widgets 

random.seed() 
notation = "" 
output = """This is 
an example of a lot of crap 
that will be displayed here 
if I ever get 
this to work 
and this is a really long line -Super Cali Fragil Istic Expi Ali Docious 
""" 

# Dice notation entry field, and it's label 

notation_entry = ttk.Entry(mainframe, width=10, textvariable=notation) 
notation_entry.grid(column=2, row=1) 
ttk.Label(mainframe, text="Dice").grid(column=1, row=1) 

# Section used for output 
"""Huge laundry list of problems here: 

1. textvariable is not displaying anything here. If I change it to text 
    it seems to work, but from what I can tell, that will not update. 
2. I would love for it to have a static height, but height is not allowed here. 
    Need to figure out a workaround. 
3. Also, have not figured out how to get the value returned by calculate() 
    to show up in here when the button is pressed...""" 

output_message = Message(mainframe, textvariable=output, width= 600) 
output_message.grid(column=1, row=2, rowspan=3, columnspan=3) 

# The 'make it go' button. 
"""Can I pass the function a variable?""" 

ttk.Button(mainframe, text="Roll!", command=calculate).grid(column=3, row=5) 


# This is a bunch of stuff from the command line version of this program. 
# Only here for reference 

"""while True: 
    notation = raw_input('Please input dice notation or q to quit: ') 

    if notation == "q": 
     raise SystemExit 
    else: 
     print(notation) 

     numbers = parse(notation) 
     (dice, dtype, mod) = numbers 

     total = roll(dice, dtype) 
     total += mod 

     print('Your total is %d' % total)""" 


dice.mainloop() 

回答

0

创建对象的字符串变量需要来代替普通的字符串变量,当您使用textvariable的时候,我改变了你的变量符号的字符串变量

notation = StringVar() 
notation.set("") 

然后拿到在计算子符号的价值我用

print(notation.get()) 

您的代码,我已编辑在全beneth粘贴

#!/usr/bin/env python 

from tkinter import * 
from tkinter import ttk 
import re 
import random 

# Parsing function from the original command line tool 
# Turns dice notation format into useful variables 

def parse(d): 
    dice, dtype_mod = d.split('d') 

    dnum = 1 
    dtype = 6 
    mod = 0 

    if dtype_mod: 
     if '-' in dtype_mod: 
      dtype, mod = dtype_mod.split('-') 
      mod = -1 * int(mod) 
     elif '+' in dtype_mod: 
      dtype, mod = dtype_mod.split('+') 
      mod = int(mod) 
     else: 
      dtype = dtype_mod 
    if not dtype: dtype = 6 
    if not mod: mod = 0 

    return (int(dice), int(dtype), int(mod)) 

# Rolling function from the original command line tool 
# 'print()' will be changed into a variable, with the output 
# appended in the working version. 

def roll(a, b): 
    rolls = [] 
    t = 0 

    for i in range(a): 
     rolls.append(random.randint(1, b)) 
     t += int(rolls[i]) 
     print(('Roll number %d is %s, totaling %d') % (i + 1, rolls[i], t)) 
    return (int(t)) 

# Placeholder - the rest of the command line code will be used here later 
# This code will be what starts everything rolling. 
# For debugging, attempting to pass a variable, doing it wrong. 

def calculate(): 
    print(notation.get()) 
    output = "this is something different" 
    return output 

# Initialize 

dice = Tk() 
dice.title('Roll the Dice') 
dice.geometry("800x600+20+20") 

# Drawing the main frame 

mainframe = ttk.Frame(dice, padding="3 3 12 12") 
mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) 
mainframe.columnconfigure(0, weight=1) 
mainframe.rowconfigure(0, weight=1) 

# Variables needed for program and widgets 

random.seed() 
notation = StringVar() 
notation.set("") 
output = """This is 
an example of a lot of crap 
that will be displayed here 
if I ever get 
this to work 
and this is a really long line -Super Cali Fragil Istic Expi Ali Docious 
""" 

# Dice notation entry field, and it's label 

notation_entry = ttk.Entry(mainframe, width=10, textvariable=notation) 
notation_entry.grid(column=2, row=1) 
ttk.Label(mainframe, text="Dice").grid(column=1, row=1) 

# Section used for output 
"""Huge laundry list of problems here: 

1. textvariable is not displaying anything here. If I change it to text 
    it seems to work, but from what I can tell, that will not update. 
2. I would love for it to have a static height, but height is not allowed here. 
    Need to figure out a workaround. 
3. Also, have not figured out how to get the value returned by calculate() 
    to show up in here when the button is pressed...""" 

output_message = Message(mainframe, textvariable=output, width= 600) 
output_message.grid(column=1, row=2, rowspan=3, columnspan=3) 

# The 'make it go' button. 
"""Can I pass the function a variable?""" 

ttk.Button(mainframe, text="Roll!", command=calculate).grid(column=3, row=5) 


# This is a bunch of stuff from the command line version of this program. 
# Only here for reference 

"""while True: 
    notation = raw_input('Please input dice notation or q to quit: ') 

    if notation == "q": 
     raise SystemExit 
    else: 
     print(notation) 

     numbers = parse(notation) 
     (dice, dtype, mod) = numbers 

     total = roll(dice, dtype) 
     total += mod 

     print('Your total is %d' % total)""" 


dice.mainloop()