简体   繁体   中英

how do you not print if x is the same?

I'm kind of a newbie in 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. 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

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.

That said I replace your import of tkinter to be import tkinter as tk . This will help prevent overwriting anything being imported. Just good practice.

Here is a non OOP example.

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. This helps you prevent the need to use 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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