为什么我不能在第二次运行时运行代码?

2024-10-02 06:23:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码在第一次运行时不是错误的,但在第二次运行后(尚未关闭窗口)是错误的。这是我的代码:

    import tkinter as tk
    from tkinter import *

    window = tk.Tk()
    window.state('zoomed')

    Harga = []

    inputH = IntVar(window)
    inputJ = IntVar(window)
    harga = Entry(window, width = 80, textvariable = inputH)
    jumlah = Entry(window, width = 80, textvariable = inputJ)

    def mat():
      global harga, jumlah, total, teks, Harga
      harga = int(harga.get())
      jumlah = int(jumlah.get())
      total = harga * jumlah
      print(total)
      return mat

    tombol = FALSE
    def perulangan():
      global tombol
      tombol = TRUE
      if tombol == TRUE:
        mat()
      else:
        pass
     return perulangan


   tombol = Button(window, text = "Submit", command = perulangan)
   keluar = Button(window, text = "Quit", background = 'red')

   harga.pack()
   jumlah.pack()
   tombol.pack()
   keluar.pack()
   window.mainloop()
    

如果我第一次输入5000*4这样的整数,这就是输出:

  20000

如果我在第二个输入另一个整数,比如2000*2,我会得到错误:

  AttributeError: 'int' object has no attribute 'get'

我希望大家都明白我的要求,谢谢


Tags: 代码importgettkinter错误windowpacktk
1条回答
网友
1楼 · 发布于 2024-10-02 06:23:08

由于您使用全局变量存储文本字段,因此不能将其作为输入值的变量重用

要解决这个问题,只需使用一个新变量来存储从文本字段中提取的值

def mat():
  global harga, jumlah, total
  harga_value = int(harga.get())
  jumlah_value = int(jumlah.get())
  total = harga_value * jumlah_value
  return mat

相关问题 更多 >

    热门问题