【问题标题】:Can't figure out how to use a variable from one function in another - Python无法弄清楚如何在另一个函数中使用一个函数的变量 - Python
【发布时间】:2019-11-24 16:05:40
【问题描述】:

我正在做一个小项目来帮助我巩固对 python 的学习。经过无休止的全局变量尝试,并返回;和搜索我决定在这里发帖。基本上,当程序运行时,用户可以从他们的计算机中选择一个 .txt 文件,然后通过 findFile() 函数特别是 my_label 变量记录目录。我想使用存储在 my_label 中的字符串将其放在 editFile 函数中,特别是以下行: my_file = open("File location goes here","a+") 其中看起来像 my_file = open(my_label,"a+" )。如果有人能提供帮助,我将不胜感激。

root = tk.Tk()

canvas1 = tk.Canvas(root, width = 400, height = 300)
canvas1.pack()

entry1 = tk.Entry (root) 
canvas1.create_window(200, 140, window=entry1)

def editFile ():

    x1 = entry1.get()

    label1 = tk.Label(root, text=x1 )
    canvas1.create_window(200, 230, window=label1)

    my_file = open("File location goes here","a+")

    my_file.read()

    my_file.write("\n" + x1)

    my_file.close()

def findFile ():
    root.filename = filedialog.askopenfilename(initialdir="C:\\Users\\mypc", 
title="Select A File", filetypes=(("txt files", "*.txt"),("All Files", "*.*"))) 
    my_label = Label(root, text=root.filename).pack() 
    canvas1.create_window(200, 290, window=my_label)

button1 = tk.Button(text='Enter Text', command=editFile)
canvas1.create_window(200, 180, window=button1)

button2 = tk.Button(text='Exit', command=root.destroy)
canvas1.create_window(200, 250, window=button2)

button3 = tk.Button(text='Find File', command=findFile)
canvas1.create_window(200, 270, window=button3)

root.mainloop()

【问题讨论】:

  • my_label 中,您既不存储任何字符串,也不存储Label,而是None,因为pack() 总是返回None。您必须分两步完成my_label = tk.Label()my_label.pack()。但是你在root.filename 中有你的文本,所以在editFile 中使用它。
  • “在对全局变量进行无休止的尝试后,然后返回”:阅读Best way to structure a tkinter application 以摆脱使用global
  • 如果你把小部件 (my_label') on Canvas then you don't need pack()/grid()/place()`

标签: python function file variables tkinter


【解决方案1】:

findFile() 中,您应该使用global filename 将值放入全局变量filename,而不是创建本地变量。

editFile() 中,您不必使用global,因为您只从变量中读取值。

但最好在启动时设置默认值filename = '',这样您就可以检查是否选择了文件名,并且不会引发错误"variable doesn't exist"


顺便说一句:一开始我创建了没有文本的标签,后来我更改了现有标签中的文本,而不是在选择不同文件时一次又一次地创建标签。


import tkinter as tk
from tkinter import filedialog

def editFile():
    #global filename # doesn't need to get value from global variable

    print(filename)

    text = entry1.get()

    # update text in existing `Label`
    label_text['text'] = text

    if filename: # dont't write if filename is not selected
        my_file = open(filename, "a")
        my_file.write("\n" + text)
        my_file.close()
    else:
        print('no filename')

def findFile():
    global filename # inform function to put value in global variable instead of creating local one

    filename = filedialog.askopenfilename(
        initialdir="C:\\Users\\mypc", 
        title="Select A File",
        filetypes=(("txt files", "*.txt"), ("All Files", "*.*"))
    )

    # update text in existing `Label`
    label_filename['text'] = filename

# --- main ---

filename = '' # (global variable) default value at start

root = tk.Tk()

canvas1 = tk.Canvas(root, width = 400, height = 300)
canvas1.pack()

entry1 = tk.Entry (root) 
canvas1.create_window(200, 140, window=entry1)

button1 = tk.Button(text='Enter Text', command=editFile)
canvas1.create_window(200, 180, window=button1)

button2 = tk.Button(text='Exit', command=root.destroy)
canvas1.create_window(200, 250, window=button2)

button3 = tk.Button(text='Find File', command=findFile)
canvas1.create_window(200, 270, window=button3)

# create only once and without text
label_filename = tk.Label(root)
canvas1.create_window(200, 290, window=label_filename)

# create only once and without text
label_text = tk.Label(root)
canvas1.create_window(200, 230, window=label_text)

root.mainloop()

【讨论】:

  • 谢谢你帮助了很多人。它运行良好,您帮助我格式化并更好地理解您编写的代码。 =)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-11
  • 1970-01-01
  • 1970-01-01
  • 2013-04-22
  • 2016-02-26
  • 1970-01-01
  • 2012-09-28
相关资源
最近更新 更多