debugging 为什么我的Python Tkinter按钮不显示

hpcdzsge  于 2023-05-07  发布在  Python
关注(0)|答案(1)|浏览(164)

我最近在学习Tkinter,我想尝试构建一个在线程序,允许人们创建文档并编辑它们,或者在Tkinter窗口中创建它们。但是,由于某种原因,我的代码没有显示应该保存和写入文件的Tkinter按钮。忘记编辑文档部分,我想首先解决这个问题。

from tkinter import *
action = input("Do you want to create or edit a doc? c for create, e for edit:\n").lower()

if action == 'c':
  name = input("What do you want to name your document? ").lower()
  fs = open(name + ".txt", 'w')
  txtData = ""
  tab = Tk()
  tab.geometry('500x400')
  tab.resizable(0,0)
  inputTxt = Text(tab, width = 200, height = 100, padx = 30, pady = 30)
  inputTxt.pack()
  def save():
    inputTxtGet = inputTxt.get(1.0, 'end-1c')
    txtData = inputTxtGet
    fs.write(txtData)
    fs.close()
  saveBtn = Button(tab, text = "Write and Save", command = save, background = "green", activebackground = "lime").pack()

我不明白哪里出了问题,因为没有错误出现。请帮我调试一下。

bt1cpqcv

bt1cpqcv1#

但是,由于某种原因,我的代码没有显示应该保存和写入文件的Tkinter按钮。忘记编辑文档部分,我想首先解决这个问题。
标签对象必须从顶部开始。
ButtonEntry小部件移到函数之外。
Snippet重写:

from tkinter import *

tab = Tk()
tab.geometry('500x400')
   

action = input("Do you want to create or edit a doc? c for create, e for edit:\n").lower()

if action == 'c':
  name = input("What do you want to name your document? ").lower()
  fs = open(name + ".txt", 'w')
  txtData = ""
   
   
def save():
    inputTxtGet = inputTxt.get(1.0, 'end-1c')
    txtData = inputTxtGet
    fs.write(txtData)
    fs.close()
    
saveBtn = Button(tab, text = "Write and Save", command = save, background = "green", activebackground = "lime").pack()
inputTxt = Text(tab, width = 200, height = 100, padx = 30, pady = 30)
inputTxt.pack()

tab.mainloop()

获取用户输入后的屏幕截图:

相关问题