如何在tkinter中使用文本框并使用这些值?蟒蛇3

Kar*_*ara 1 python user-interface tkinter

如何在tkinter中的条目小部件中创建多行并使用这些输入来创建一些东西?例如,我想要一个文本框小部件出现并询问用户:

How many squares do you want? (ex: 4x4, 5x5)
What color do you want them?
Run Code Online (Sandbox Code Playgroud)

随着用户输入,我想在特定的高度/宽度创建许多x量的正方形并指定颜色等.我对tkinter完全不熟悉,我不确定如何处理这个问题.

我尝试使用它,但我不确定如何添加更多行并使用输入的值.

import tkinter
from tkinter import *

class Squares:
    root = Tk()
    root.title('Random')
    x = Label(text='How many squares? (ex: 4x4, 5x3)').pack(side=TOP,padx=10,pady=10)
    Entry(root, width=10).pack(side=TOP,padx=10,pady=10)
    Button(root, text='OK').pack(side= LEFT)
    Button(root, text='CLOSE').pack(side= RIGHT)
Run Code Online (Sandbox Code Playgroud)

aba*_*ert 8

你在这里遇到了很多问题.

我不确定该Squares课程应该做什么,但它基本上没有做任何事情.你有一堆代码在你定义类时运行,创建一些变量(最终将作为类属性,由类的所有实例共享),以及......就是这样.而不是试图弄清楚你在这里想要什么,我只是要废弃这个类并将其作为所有模块级代码.

你永远不会打电话root.mainloop(),所以你的程序只会定义一个GUI,然后永远不会运行它.

您不会将按钮绑定到任何东西,因此它们无法产生任何效果.你需要创建某种功能,然后将其作为command参数传递,或者.bind稍后传递.

您不存储任何控件的引用,因此以后无法访问它们.如果要从条目中获取值,则需要某种方式来引用它.(例外是你的x变量,但那将是None,因为你将它设置为调用packLabel不是Label自身的结果.)

一旦你完成了,你只需要解析值,这很容易.

把它们放在一起:

import tkinter
from tkinter import *

root = Tk()
root.title('Random')
Label(text='How many squares? (ex: 4x4, 5x3)').pack(side=TOP,padx=10,pady=10)

entry = Entry(root, width=10)
entry.pack(side=TOP,padx=10,pady=10)

def onok():
    x, y = entry.get().split('x')
    for row in range(int(y)):
        for col in range(int(x)):
            print((col, row))

Button(root, text='OK', command=onok).pack(side=LEFT)
Button(root, text='CLOSE').pack(side= RIGHT)

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

你只需改变它print来做一些有用的事情,比如创建正方形.