简体   繁体   English

如果 x 相同,你怎么不打印?

[英]how do you not print if x is the same?

I'm kind of a newbie in python.我是 python 的新手。 I want to create a program that when you copy something to your clipboard, It 'prints' it on the 'app'.我想创建一个程序,当您将某些内容复制到剪贴板时,它会在“应用程序”上“打印”它。 It works, but the issue is that every two seconds it displays what you may have copied 2 hours ago.它可以工作,但问题是每两秒钟它就会显示你在 2 小时前可能复制的内容。 I want it to be that when the clipboard is the same, it only shows one time and then it waits until you have copied something else.我希望它是当剪贴板相同时,它只显示一次,然后等到你复制了其他东西。 This is what i have so far这就是我到目前为止所拥有的

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()

Thank you!谢谢!

you could make a variable called old_x, store the last value of x in there, and put an if-statement around the Label line, so that it only prints if x is not old_x您可以创建一个名为 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()

You can simply add an IF statement to check the old value of x and then update when needed.您可以简单地添加一个 IF 语句来检查 x 的旧值,然后在需要时进行更新。

That said I replace your import of tkinter to be import tkinter as tk .也就是说,我将您导入的 tkinter 替换为import tkinter as tk This will help prevent overwriting anything being imported.这将有助于防止覆盖正在导入的任何内容。 Just good practice.只是好习惯。

Here is a non OOP example.这是一个非 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()

Here is an OOP example.这是一个 OOP 示例。 This helps you prevent the need to use global .这有助于您避免使用global In general it is good to avoid global.一般来说,最好避免全局。 There are some good post about this if you want to know more.如果您想了解更多信息,有一些关于此的好帖子。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM