如何使用tkinter条目作为函数的参数

时间:2018-04-27 18:06:26

标签: python python-2.7 tkinter

我想要一个文本框在tkinter窗口中询问输入,然后使用该输入作为参数来调用绘制Sierpinski三角形的函数。我的按钮工作,但我的输入框没有。我一直在努力修复我的代码,但它没有用,任何帮助都会受到赞赏。

import tkinter as tk
from tkinter import *

root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
root.title('Fractals') #titles the button box

top_frame = tk.Frame()
mid_frame = tk.Frame()

prompt_label = tk.Label(top_frame, \
       text='Enter a number of iterations (more is better):')
iterations = tk.Entry(root,bd=1)

itr=iterations.get()
itr=int(itr)

button = tk.Button(frame, 
                   text="QUIT", 
                   fg="red",
                   command=quit)
button.pack(side=tk.LEFT)

sTriangle = tk.Button(frame,
                   text="Triangle",
                   command=lambda: sierpinski(fred, (-500,-500), (500,-500), 
(0,500),itr))
sTriangle.pack(side=tk.LEFT)

fsquare = tk.Button(frame,
                    text="Square",
                    command=fractalsquare(fred,(-500,-500),(500,-500), 
(500,500),(-500,500),itr))
fsquare.pack(side=tk.LEFT)

root.mainloop()

1 个答案:

答案 0 :(得分:0)

有几个问题:

1)选择一种方式导入tkinter或导致混淆

2)你应该为你的Frames提供一个master,然后打包它们。注意框架的出现位置和包含的内容。

3)通常会为Entry分配一个textvariable,它将包含你输入的内容。 textvariable应该是tk.StringVar。

4)如果Button有回调函数,则必须在创建按钮之前定义它。

5)未定义变量fred。

如何编写它的示例:

import tkinter as tk

root = tk.Tk()
root.title('Fractals') #titles the button box

# Create the Label at the top
top_frame = tk.Frame(root)  # Top Frame for 
top_frame.pack()
prompt_label = tk.Label(top_frame,
                        text='Enter a number of iterations (more is better):')
prompt_label.pack()

# Create the Entry in the middle
mid_frame = tk.Frame(root)
mid_frame.pack()
itr_string = tk.StringVar()
iterations = tk.Entry(mid_frame,textvariable=itr_string)
iterations.pack()

fred=None   # Was not defined...

# Create Buttons at the bottom
bot_frame = tk.Frame(root)
bot_frame.pack()
button = tk.Button(bot_frame, text="QUIT", fg="red", command=quit)
button.pack(side=tk.LEFT)

def sierpinski(*args):  # sTriangle button callback function
    itr = int(itr_string.get())   # How to get text from Entry
    # if Entry does not contain an integer this will throw an exception

sTriangle = tk.Button(bot_frame, text="Triangle",
    command=lambda: sierpinski(fred, (-500,-500), (500,-500),(0,500),itr_string))
sTriangle.pack(side=tk.LEFT)

def fractalsquare(*args): pass     # fsquare button callback function

fsquare = tk.Button(bot_frame, text="Square", command=fractalsquare(fred,
    (-500,-500),(500,-500),(500,500),(-500,500),itr_string))
fsquare.pack(side=tk.LEFT)

root.mainloop()

你应该认真学习基本的tkinter教程。试试这个:An Introduction To Tkinter