从.txt文件提取数据,使用变量发布

2ic8powd  于 2021-08-25  发布在  Java
关注(0)|答案(0)|浏览(251)

我从一个.txt文件中提取数据,这个文件是我自己创建的数据库。我特意将文件每行中的最后一个参数设置为图像的名称。
因为我想把一个按钮链接到它对应的图像上。当我单击按钮时,相应的图像将打开。

import sys
from tkinter import *
import tkinter as tk
from PIL import Image

class Application(tk.Frame):
    x = 2

    def __init__(self, param = None, i = None, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()

def create_widgets(self):

    if (self.x == 2):
        param = "coucou"
    self.hi_there = tk.Label(self)
    self.hi_there["text"] = param
    #self.hi_there["command"] = self.say_hi
    self.hi_there.pack(side="top")

    self.quit = tk.Button(self, text="QUIT", fg="red",
                          command=self.master.destroy)
    self.quit.pack(side="bottom")

    # Opening file in read format
    File = open('data.txt',"r")
    if(File == None):
        print("File Not Found..")
    else:
        while(True):
            # extracting data from records 
            record = File.readline()
            if (record == ''): break
            data = record.split(',')
            print('Name of the dish:', data[0])
            self.hi_there = tk.Button(self)
            self.hi_there["text"] = data[0]
            self.hi_there["command"] = self.photoOfTheDish
            self.hi_there.pack(side="top")
            # printing each record's data in organised form
            for i in range(1, len(data)-1):
                print('Ingredients:',data[i])
                self.hi_there = tk.Label(self)
                self.hi_there["text"] = data[i]
                self.hi_there.pack(side="top")
    File.close()

def photoOfTheDish(self):
    i = "0.ppm"
    novi = Toplevel()
    self.canvas = Canvas(novi, width = 1500, height = 1000)
    self.canvas.pack(expand = YES, fill = BOTH)
    File = open('data.txt',"r")
    with open('data.txt') as f:
        record = File.readline()
        data = record.split(',')
        print(data[-1], i)
        gif1 = PhotoImage(file = data[-1])
                                        #image not visual
        self.canvas.create_image(50, 10, image = gif1, anchor = NW)
        #assigned the gif1 to the canvas object
        self.canvas.gif1 = gif1

root = tk.Tk()
root.geometry("5000x2000")
app = Application(master=root)
app.mainloop()

在函数中 photoOfTheDish ,我想打开每行最后一个变量对应的图像,这就是为什么我 data[-1] 在这里: gif1 = PhotoImage(file = data[-1]) 数据[-1]的值是0.ppm,您可以看到i的值也是0.ppm。当我写作时 gif1 = PhotoImage(file = i) 它在工作,但当我写的时候 gif1 = PhotoImage(file = data[-1]) 它不起作用了。我不明白为什么?有相同的精确值!

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题