[英]how do you not print if x is the same?
我是 python 的新手。 我想創建一個程序,當您將某些內容復制到剪貼板時,它會在“應用程序”上“打印”它。 它可以工作,但問題是每兩秒鍾它就會顯示你在 2 小時前可能復制的內容。 我希望它是當剪貼板相同時,它只顯示一次,然后等到你復制了其他東西。 這就是我到目前為止所擁有的
import pyperclip
from tkinter import *
r = Tk()
def aper():
global x
x = pyperclip.waitForPaste()
Label(r, text = x).pack()
r.after(2000, aper)
r.after(2000, aper)
r.mainloop()
謝謝!
您可以創建一個名為 old_x 的變量,將 x 的最后一個值存儲在其中,並在 Label 行周圍放置一個 if 語句,以便僅在 x 不是 old_x 時打印
import pyperclip
from tkinter import *
r = Tk()
def aper():
global x
global old_x
x = pyperclip.waitForPaste()
if x != old_x:
Label(r, text = x).pack()
old_x = x
r.after(2000, aper)
old_x = None
r.after(2000, aper)
r.mainloop()
您可以簡單地添加一個 IF 語句來檢查 x 的舊值,然后在需要時進行更新。
也就是說,我將您導入的 tkinter 替換為import tkinter as tk
。 這將有助於防止覆蓋正在導入的任何內容。 只是好習慣。
這是一個非 OOP 示例。
import tkinter as tk
import pyperclip
r = tk.Tk()
x = ''
def aper():
global x
y = pyperclip.waitForPaste()
if x != y:
x = y
tk.Label(r, text=x).pack()
r.after(2000, aper)
r.after(2000, aper)
r.mainloop()
這是一個 OOP 示例。 這有助於您避免使用global
。 一般來說,最好避免全局。 如果您想了解更多信息,有一些關於此的好帖子。
import tkinter as tk
import pyperclip
class App(tk.Tk):
def __init__(self):
super().__init__()
self.x = ''
print('t')
def aper(self):
y = pyperclip.waitForPaste()
if self.x != y:
self.x = y
tk.Label(self, text=self.x).pack()
self.after(2000, self.aper)
if __name__ == '__main__':
App().mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.